<?php

namespace app\admin\service;

use app\admin\models\ExpressModel;
use think\Log;

class KdniaoService
{
    # 快递公司编码和名称映射关系
    private $shipper = [
        'ZTO' => '中通快递',
        'YTO' => '圆通速递',
        'YD' => '韵达速递',
        'STO' => '申通快递',
        'SF' => '顺丰速运',
        'JD' => '京东快递',
        'YZPY' => '邮政快递包裹',
        'EMS' => 'EMS',
        'JTSD' => '极兔速递',
        'DBL' => '德邦快递',
        'FWX' => '丰网速运',
        'HTKY' => '百世快递',
        'DNWL' => '东骏快捷物流',
        'FEDEX' => 'FEDEX联邦（国内）',
        'RRS' => '日日顺物流',
        'ANEKY' => '安能快运/物流',
        'ZTOKY' => '中通快运',
        'ANE' => '安能快递',
        'SX' => '顺心捷达',
        'BTWL' => '百世快运',
        'XFEX' => '信丰物流',
        'YMDD' => '壹米滴答',
        'JGSD' => '京广速递',
        'DBLKY' => '德邦快运/德邦物流',
        'KYSY' => '跨越速运',
        'JDKY' => '京东快运',
        'YDKY' => '韵达快运',
        'TJS' => '特急送',
        'UPS' => 'UPS',
        'YAD' => '源安达快递',
        'ANNTO' => '安得物流',
        'LHT' => '联昊通速递',
        'ZJS' => '宅急送',
        'YF' => '耀飞快递',
        'USPS' => 'USPS美国邮政',
        'DHL' => 'DHL-中国件',
        'FASTGO' => '速派快递',
        'HSSY' => '汇森速运',
        'JYM' => '加运美',
        'ZTOGLOBAL' => '中通国际',
        'UC' => '优速快递',
        'HOAU' => '天地华宇',
        'TNJEX' => '明通国际快递',
        'DPDUK' => 'DPD(UK)',
        'DSWL' => 'D速物流',
        'EWE' => 'EWE',
        'SHWL' => '盛辉物流',
        'YJWL' => '云聚物流',
        'ZY_FY' => '飞洋快递',
        'YXWL' => '宇鑫物流',
        'PADTF' => '平安达腾飞快递',
        'ZYE' => '众邮快递',
        'UBONEX' => '优邦国际速运',
        'ZHONGTIEWULIU' => '中铁飞豹',
        'HDWL' => '宏递快运',
        'CRAZY' => '疯狂快递',
        'STWL' => '速腾快递',
        'CTWL' => '长通物流',
        'PANEX' => '泛捷快递',
        'LB' => '龙邦快递',
        'BETWL' => '百腾物流',
        'AUEXPRESS' => '澳邮中国快运AuExpress',
        'ESDEX' => '卓志速运',
        'SFWL' => '盛丰物流',
        'JP' => '日本邮政',
        'ZY100' => '中远快运',
        'HTB56' => '徽托邦物流',
        'YBG' => '洋包裹',
        'ZTWL' => '中铁物流',
        'ZHONGHUAN' => '中环国际快递',
        'HTWL' => '鸿泰物流',
        'BCTWL' => '百城通物流',
        'SNWL' => '苏宁物流',
        'TU' => '运联科技',
        'TBZS' => '特宝专送',
        'FTD' => '富腾达',
        'JIUYE' => '九曳供应链',
        'CSTD' => '畅顺通达',
        'HISENSE' => '海信物流',
        'AUODEXPRESS' => '澳德物流',
        'GJYZBG' => '国际邮政包裹',
        'YLFWL' => '一路发物流',
        'WHXBWL' => '武汉晓毕物流',
        'YSDF' => '余氏东风',
        'JAD' => '捷安达',
        'AUEX' => '澳货通',
        'SUBIDA' => '速必达物流',
        'SYJWDX' => '佳旺达物流',
        'ROYALMAIL' => 'RoyalMail',
        'FZGJ' => '方舟国际速递',
        'XJ' => '新杰物流',
        'TNT' => 'TNT国际快递',
        'SENDCN' => '速递中国',
        'EMSBG' => 'EMS包裹',
        'DTWL' => '大田物流',
        'D4PX' => '递四方速递',
        'CJKOREAEXPRESS' => '大韩通运',
        'JGWL' => '景光物流',
        'CJEXPRESS' => '长江国际速递',
        'CITY56' => '城市映急',
        'CHT361' => '诚和通',
        'ONEEXPRESS' => '一速递',
        'XDEXPRESS' => '迅达速递',
        'BN' => '笨鸟国际',
        'NSF' => '新顺丰国际速递',
        'EPOST' => '韩国邮政',
        'JUMSTC' => '聚盟共建',
        'TAQBINJP' => 'Yamato宅急便',
        'A4PX' => '转运四方',
        'DEKUN' => '德坤',
        'COE' => 'COE东方快递',
        'DFWL' => '达发物流',
        'TZKY' => '铁中快运',
        'LYT' => '联运通物流',
        'DHLGLOBALLOGISTICS' => 'DHL全球货运',
        'SWEDENPOST' => '瑞典邮政',
        'BEEBIRD' => '锋鸟物流',
        'CFWL' => '春风物流',
        'JYWL' => '佳怡物流',
        'XYJ' => '西邮寄',
        'LINGSONG' => '领送送',
        'SJA56' => '四季安物流',
        'WTP' => '微特派',
        'HAOXIANGWULIU' => '豪翔物流',
        'HCT' => '新竹物流HCT',
        'SUYD56' => '速邮达物流',
        'YBWL' => '优拜物流',
        'COSCO' => '中远e环球',
        'GOEX' => '时安达速递',
        'IADLYYZ' => '澳大利亚邮政',
        'LHTEX' => '联昊通',
        'LNET' => '新易泰',
        'WJWL' => '万家物流',
        'AX' => '安迅物流',
        'CCES' => 'CCES/国通快递',
        'DPD' => 'DPD',
        'FAMIPORT' => '全家快递',
        'HJWL' => '汇捷物流',
        'HNTLWL' => '泰联物流',
        'HQSY' => '环球速运',
        'JTEXPRESS' => 'J&TExpress',
        'KEJIE' => '科捷物流',
        'KZWL' => '科紫物流',
        'MHKD' => '民航快递',
        'SHPOST' => '同城快寄',
        'SINGAPOREPOST' => '新加坡邮政',
        'SINGAPORESPEEDPOST' => '新加坡特快专递',
        'STSD' => '三态速递',
        'UPSEN' => 'UPS-全球件',
        'WJK' => '万家康',
        'XCWL' => '迅驰物流',
        'XLOBO' => '贝海国际速递',
        'YYSD' => '优优速递',
    ];


    // 快递鸟--快递查询
    // https://www.yuque.com/kdnjishuzhichi/dfcrg1/tb8nyy
    public function express_query($LogisticCode, $CustomerName)
    {
        if (!isset($LogisticCode) || empty($LogisticCode)) return false;

        $eBusinessID = config("kdniao")['EBusinessID'];
        $appKey = config("kdniao")['ApiKey'];
        $apiUrl = config("kdniao")['Url'];
        $requestData = [
            'LogisticCode' => $LogisticCode
        ];
        if (isset($CustomerName) && !empty($CustomerName) ) {
            $requestData['CustomerName'] = substr($CustomerName, -4);
        }
        $requestDataJson = json_encode($requestData);

        $dataSign = base64_encode(md5($requestDataJson . $appKey));

        $postData = [
            'RequestData' => urlencode($requestDataJson),
            'EBusinessID' => $eBusinessID,
            'RequestType' => '8002',
            'DataSign' => $dataSign,
            'DataType' => '2'
        ];

        $response = send_request($apiUrl, 'POST', $postData);
        if ($response === false) {
            return false;
        }
        $response = (array)json_decode($response);

        if (isset($response['Success']) && $response['Success']) {
            Log::record("kdniao succ, LogisticCode: " . $LogisticCode . ", result: " . json_encode($response));
            return $response;
        } else {
            Log::record("kdniao fail, LogisticCode: " . $LogisticCode . ", result: " . json_encode($response));
            return false;
        }
    }

    public function express_query_job()
    {
        $ExpressModel = new ExpressModel();

        $list = obj_to_arr($ExpressModel->field("express_id,logistic_code,sender_mobile")
            ->whereNotIn('state', ['4', '5', '6'])
            ->whereNull('state', 'OR')
            ->select());
        foreach ($list as $item) {
            if (!empty($item['logistic_code'])) {
                $response = $this->express_query($item['logistic_code'], $item['sender_mobile']);
                if ($response) {
                    $ExpressModel->where('express_id', $item['express_id'])->update([
                        'shipper_name' => $this->shipper[$response['ShipperCode']],
                        'state' => $response['State'],
                        'state_ex' => $response['StateEx'],
                        'reason' => $response['Reason'],
                        'location' => $response['Location'],
                        'response_data' => json_encode($response),
                    ]);
                }
                sleep(1);
            }
        }
    }

    public function express_one($LogisticCode, $CustomerName)
    {
        if (empty($LogisticCode)) return;

        $response = $this->express_query($LogisticCode, $CustomerName);
        if ($response) {
            (new ExpressModel())->where('logistic_code', $LogisticCode)->update([
                'shipper_name' => $this->shipper[$response['ShipperCode']],
                'state' => $response['State'],
                'state_ex' => $response['StateEx'],
                'reason' => $response['Reason'],
                'location' => $response['Location'],
                'response_data' => json_encode($response),
            ]);
        }
    }

}
